<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\SettingFinance;
use App\Models\SettingGain;
use App\Models\SettingMedia;
use App\Models\SettingMessage;
use App\Models\SettingPay;
use App\Models\SettingWechat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class SettingController extends Controller
{
    /**
     * 获取系统所有配置项
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function index()
    {
        $Setting = Setting::first();
        if(!$Setting) {
            DB::beginTransaction();
            try {
                $Setting = Setting::create([
                    'website_name' => '有趣红包'
                ]);
                $Setting->wechat()->save(new SettingWechat([
                    'wechat_token' => Str::random(32),
                    'wechat_encoding_key' => Str::random(43)
                ]));
                $Setting->pay()->save(new SettingPay([
                    'wechat_mch_key' => Str::random(32)
                ]));
                $Setting->finance()->save(new SettingFinance());
                $Setting->gain()->save(new SettingGain());
                $Setting->media()->save(new SettingMedia());
                $Setting->message()->save(new SettingMessage());
                DB::commit();
                return $this->index();
            } catch (\PDOException $e) {
                DB::rollBack();
                return response($e->getMessage(), 501);
            }
        } else {
            $Setting->wechat;
            $Setting->pay;
            $Setting->finance;
            $Setting->finance->low_deposit = \Kuyuan\Phpwidget\Str::format_money($Setting->finance->low_deposit);
            $Setting->finance->deposit_check = \Kuyuan\Phpwidget\Str::format_money($Setting->finance->deposit_check);
            $Setting->gain;
            $Setting->media;
            $Setting->message;
            return response(["data"=>$Setting]);
        }
    }

    /**
     * 修改配置
     * @param string $_type 修改的配置类型
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function update($_type,Request $request)
    {
        $_setting_id = $Setting = Setting::value("id");
        switch ($_type) {
            case 'base':
                $_data = $request->input();
                if(isset($_data['notice']) && $_data['notice'] != Setting::value('notice')) {
                    $_data['notice_time'] = time();
                }
                $_result = Setting::where("id",$_setting_id)->update($_data);
                break;
            case 'wechat':
                $_data = $request->input();
                // 公众号导航设置
                if($_data['wechat_navs'] === null || isset($_data['wechat_navs'])) {
                    $_set_navs_response = $this->setWechatNavs($_data['wechat_navs']);
                    if($_set_navs_response['errcode'] != 0) {
                        $_data = [];
                    }
                }
                $_result = SettingWechat::where("setting_id",$_setting_id)->update($_data);
                break;
            case 'pay':
                $_result = SettingPay::where("setting_id",$_setting_id)->update($request->input());
                break;
            case 'finance':
                $_data = $request->input();
                if(isset($_data['low_deposit'])){
                    $_data['low_deposit'] = \Kuyuan\Phpwidget\Str::format_money($_data['low_deposit'],true);
                }
                if(isset($_data['deposit_check'])) {
                    $_data['deposit_check'] = \Kuyuan\Phpwidget\Str::format_money($_data['deposit_check'],true);
                }
                $_result = SettingFinance::where("setting_id",$_setting_id)->update($_data);
                break;
            case 'gain':
                $_result = SettingGain::where("setting_id", $_setting_id)->update($request->input());
                break;
            case 'media':
                $_result = SettingMedia::where("setting_id", $_setting_id)->update($request->input());
                break;
            case 'message':
                $_result = SettingMessage::where("setting_id", $_setting_id)->update($request->input());
                break;
        }
        return $_result ? response('修改成功') : response(['message'=>'修改失败'],500);
    }

    /**
     * 上传支付证书
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function uploadWxPayCert(Request $request)
    {
        $File = $request->file('file');
        try{
            if($File->getClientOriginalName() != 'apiclient_cert.pem' && $File->getClientOriginalName() != 'apiclient_key.pem') {
                throw new \Exception('请上传正确的商户证书[1]', 403);
            }
            if($File->getSize() / 1024 > 3) {
                throw new \Exception('请上传正确的商户证书[2]', 403);
            }
            $_setting_id = Setting::value('id');
            if($File->getClientOriginalName() == 'apiclient_cert.pem') {
                $_result = SettingPay::where("setting_id",$_setting_id)->update([
                    "wechat_cert"=> Crypt::encryptString(file_get_contents($File))
                ]);
            } else {
                $_result = SettingPay::where("setting_id",$_setting_id)->update([
                    "wechat_key"=> Crypt::encryptString(file_get_contents($File))
                ]);
            }
            if(!$_result) {
                throw new \Exception('上传失败',501);
            }
            return response($_result);
        }catch (\Exception $e) {
            return response(['message'=>$e->getMessage()], $e->getCode());
        }
    }

    /**
     * 测试远程附件
     * @param $_storage_type
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function testingAttachment($_storage_type)
    {
        $_result = cool_upload_remote(public_path('logo.png'),false,true,$_storage_type);
        return $_result ? response('setting success') : response(array('message'=>'error'),401);
    }

    /**
     * 微信公众号授权所需配置
     */
    public function getOauthData()
    {
        $_data = array(
            "wechat_appid" => SettingWechat::value('wechat_appid'),
            "redirect_url" => config('app.url').'/wechat_oauth'
        );
        return response(['data'=>$_data]);
    }

    /**
     * 获取指定配置的指定字段信息
     * @param string $_setting_type
     * @param Request $request
     * @return mixed
     */
    public function getOneSetting($_setting_type, Request $request)
    {
        return response(['data'=>$this->getOnceConfig($request->input('fields'), $_setting_type)]);
    }

    /**
     * 设置微信公众号导航
     * @param $_data
     * @return mixed
     */
    private function setWechatNavs($_navs)
    {
        $Wechat = $this->wechat();
        if($_navs) {
            $_buttons = array();
            foreach($_navs as $_k=>$_value) {
                $_temp_buttons = array();
                if(isset($_value['children']) && $_value['children']) {
                    $_temp_buttons['name'] = $_value['label'];
                    foreach ($_value['children'] as $_key=>$_item) {
                        $_sub_temp_buttons = [];
                        if($_item['attribute'] == 'link'){
                            $_sub_temp_buttons['type'] = 'view';
                            $_sub_temp_buttons['url'] = $_item['value'] ? $_item['value'] : route('app');
                        } else if ($_item['attribute'] == 'app'){
                            $_sub_temp_buttons['type'] = 'click';
                            $_sub_temp_buttons['key'] = Setting::value('app_keyword');
                        }
                        $_sub_temp_buttons['name'] = $_item['label'];
                        $_temp_buttons['sub_button'][] = $_sub_temp_buttons;
                    }
                } else {
                    if($_value['status']) {
                        if($_value['attribute'] == 'link') {
                            $_temp_buttons['type'] = 'view';
                            $_temp_buttons['url'] = $_value['value'] ? $_value['value'] : route('app');
                        } else if($_value['attribute'] == 'app') {
                            $_temp_buttons['type'] = 'click';
                            $_temp_buttons['key'] = Setting::value('app_keyword');
                        }
                        $_temp_buttons['name'] = $_value['label'];
                    }
                }
                $_buttons[$_k] = $_temp_buttons;
            }
            return $Wechat->menu->create($_buttons);
        } else {
            return $Wechat->menu->delete();
        }
    }
}
